package com.epfresh.supplier.activity.employ;

import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.GsonUtil;
import com.epfresh.api.utils.InputControl;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.EmployManageAdapter;
import com.epfresh.supplier.entity.EmployEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by shenjie on 2017/9/13.
 */

public class EmployManageActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    private EditText searchEt;
    private ImageView searchIv, deleteIv;
    private ListView resultList;
    private ArrayList<EmployEntity> employListEntities = new ArrayList<>();
    private EmployManageAdapter adapter;
    private ArrayList<EmployEntity> searchListEntities = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        loadHttpRequest();
        loadMerchantResourceRequest();
    }

    private void initView() {
        toolbarTitle.setText(R.string.employ);
//        toolbarTitle.setTextColor(getResources().getColor(R.color.font_color_def));
        float textsize = getResources().getDimension(R.dimen.text_size_max_18);
        final float scale = getResources().getDisplayMetrics().density;
        float size = (textsize / scale + 0.5f);
//        toolbarTitle.setTextSize(size);
        ivBack.setVisibility(View.VISIBLE);
        righticon.setVisibility(View.VISIBLE);
        righticon.setImageResource(R.mipmap.adduser);
        righticon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EmployManageActivity.this, AddEmployActivity.class);
                startActivityForResult(intent, 100);
            }
        });
        setContentView(R.layout.activity_employ_manage);
        searchEt = (EditText) findViewById(R.id.search_et);
        searchIv = (ImageView) findViewById(R.id.search_iv);
        deleteIv = (ImageView) findViewById(R.id.delete_iv);
        deleteIv.setVisibility(View.INVISIBLE);
        resultList = (ListView) findViewById(R.id.employ_list);
        adapter = new EmployManageAdapter(this, employListEntities);
        resultList.setAdapter(adapter);
        resultList.setOnItemClickListener(this);
        searchIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (InputControl.isEmpty(searchEt)) {
                    T.toast("请输入用户姓名或手机号");
                    return;
                }
                loadHttpRequest();
            }
        });
        deleteIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEt.setText("");
            }
        });
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    deleteIv.setVisibility(View.INVISIBLE);
                } else {
                    deleteIv.setVisibility(View.VISIBLE);
                }
                if (!InputControl.isEmpty(searchEt)) {
                    searchListEntities.clear();
                    String searchStr = s.toString().trim();
                    for (EmployEntity entity : employListEntities) {
                        if ((entity.getName() + "").contains(searchStr) || (entity.getPhone() + "").contains(searchStr)) {
                            searchListEntities.add(entity);
                        }
                    }
                    adapter.setList(searchListEntities);
                } else {
                    adapter.setList(employListEntities);
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void loadHttpRequest() {
        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_employee_list);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        map.put("merchantId", getAppApplication().getMerchantId());
        map.put("name", searchEt.getText().toString().trim());
        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_employee_list, onRequestListener);
    }

    private OnRequestListener<ArrayList<EmployEntity>> onRequestListener = new OnRequestListener<ArrayList<EmployEntity>>() {
        @Override
        public ArrayList<EmployEntity> jsonToObj(String responseStr) {
            ArrayList<EmployEntity> list = GsonUtil.parseJsonArrayWithGson(responseStr, EmployEntity.class);
            return parseJsonArray(responseStr);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<ArrayList<EmployEntity>> response, Object tag) {
            employListEntities.clear();
            if (response.getResponseElement() != null) {
                employListEntities.addAll(response.getResponseElement());
            }
            adapter.notifyDataSetChanged();
            hideProgressDialog();
        }
    };


    private void loadMerchantResourceRequest() {
        //RequestEntitySupply<ArrayList<String>> data = new RequestEntitySupply<>();
        RequestEntitySupply<Map<String, Object>> data = new RequestEntitySupply<>();
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_merchant_resources);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
/*        ArrayList<String> map = new ArrayList<>();
        map.add("root.app.supplier");
        map.add("root.app.pos");*/
//        data.setParameters(map);

        Map<String, Object> map = new HashMap<>();
        map.put("showPrice", 1);
        map.put("merchantId", BaseApplication.getInstance().getMerchantId());
        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_merchant_resources, merchantListener);
    }


    private OnRequestListener<String> merchantListener = new OnRequestListener<String>() {
        @Override
        public String jsonToObj(String responseStr) {
            return responseStr;

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<String> response, Object tag) {
            Constant.resourcesStr = response.getResponseElement();
        }
    };

    private ArrayList<EmployEntity> parseJsonArray(String responseStr) {
        ArrayList<EmployEntity> arrays = null;
        try {
            JSONArray array = new JSONArray(responseStr);
            arrays = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.getJSONObject(i);
                EmployEntity entity = GsonUtil.parseJsonWithGson(object.toString(), EmployEntity.class);
                arrays.add(entity);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return arrays;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        EmployEntity entity = null;
        if (InputControl.isEmpty(searchEt)) {
            entity = employListEntities.get(position);
        } else {
            entity = searchListEntities.get(position);
        }

        if (("" + employListEntities.get(position).getAccount_id()).equals(getUser().getAccountId())) {
            toast("自己不能编辑自己的信息");
            return;
        }

        Intent intent = new Intent(this, EditEmployActivity.class);
        intent.putExtra("entity", entity);
        startActivityForResult(intent, 10);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            loadHttpRequest();
        }
    }
}
